package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"practice-hub/cache"
	"practice-hub/model"
	"practice-hub/pck"
	"strconv"
	"time"
)

func Logins(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{"code": 500, "msg":  "数据库不能为空",})
		return
	}
	redis_key := "bigcar_error_" + username
	errCout, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCout >= 3 {
		c.JSON(200, gin.H{"code": 500, "msg":  "密码错误3次，禁止登录",})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg":  "查询成功",})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg":  "账号或密码错误",})
		return
	}
	if user.Password != pck.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCout == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 2, time.Hour*2)
			c.JSON(200, gin.H{"code": 500, "msg":  "密码错误3次，禁止登录",})
			return
		} else {
			c.JSON(200, gin.H{"code": 500, "msg":  "账号或密码错误",})
			return
		}
	}
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功"})
	return
}
func AddBigCarRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	userRole := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := model.DB.Create(&userRole).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg":  "添加失败",})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg":  "添加成功",})
	return
}
func AddBigCarNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	roleNode := model.RoleNode{
		Nid: nid,
		Rid: rid,
	}
	err := model.DB.Create(&roleNode).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func BigCarUserRole(c *gin.Context) {
	uid := c.Query("uid")
	var roles []model.Role
	err := model.DB.Table("roles").
		Joins("left join user_roles on roles.id=user_roles.rid").
		Where("user_roles.uid=?", uid).
		Find(&roles).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": roles})
	return
}
func BigCarRoleNode(c *gin.Context) {
	rid := c.Query("rid")
	var nodes []model.Node
	err := model.DB.Table("nodes").
		Joins("left join role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&nodes).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": nodes})
	return
}
func AddBigCar(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_price, _ := strconv.Atoi(c.PostForm("car_price"))
	car := model.Car{
		CarCode:  car_code,
		CarName:  car_name,
		CarPrice: car_price,
	}
	err := model.DB.Create(&car).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 500, "msg": "添加成功"})
	return
}
func AddBigCarOrder(c *gin.Context) {
	order_code := c.PostForm("car_code")
	order_name := c.PostForm("car_name")
	order_price, _ := strconv.Atoi(c.PostForm("car_price"))
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order := model.CarOrder{
		OrderCode:  order_code,
		OrderName:  order_name,
		OrderPrice: order_price,
		Cid:        cid,
	}
	err := model.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 500, "msg": "添加成功"})
	return
}
func BigCarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var car []model.CarOrderList
	redis_key := "car_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").
			Select("car_orders.id AS OrderId",
				"order_code AS OrderCode",
				"order_name AS OrderName",
				"order_price AS OrderPrice",
				"car_code AS CarCode",
				"car_name AS CarName",
				"car_price As CarPrice").
			Joins("LEFT JOIN cars ON cars.id = car_orders.cid").
			Offset(offset).Limit(size).Debug().
			Order("car_orders.id").Find(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}
	var total int64
	model.DB.Model(&model.CarOrder{}).Count(&total)
	c.JSON(200, gin.H{"code":  200, "msg":   "查询成功", "data":  car, "total": total,})
	return
}
